package entry;

import domain.HttpRequest;
import domain.HttpResponse;
import handler.AcceptHandler;
import handler.ReadHandler;
import parse.XMLParse;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class HttpServer {
    public static void main(String[] args) throws IOException {

        //启动XML解析线程
        new Thread(() -> new XMLParse()).start();


        //TODO 封装为方法

        //打开 ServerSocketChannel对象
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //设置ServerSocketChannel端口号
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));
        //开启选择器
        Selector selector = Selector.open();


        //设置ServerSocketChannel为非阻塞(将通道加入选择器必须设置为非阻塞)
        serverSocketChannel.configureBlocking(false);
        //将ServerSocketChannel加入选择器
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//接受连接就绪，等待连接请求


        while (true){
            int select = selector.select();//阻塞方法，等待请求

            //发现请求向下进行
            if(select > 0){

                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();

                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    if(selectionKey.isAcceptable()){

                        //Class AcceptHandler is used for handling
                        AcceptHandler acceptHandler = new AcceptHandler(selectionKey,selector);
                        acceptHandler.handle();

                    }else if(selectionKey.isReadable()){

                        //处理读就绪的通道
                        ReadHandler readHandler = new ReadHandler(selectionKey,selector);
                        readHandler.handle();
                    }
                    iterator.remove();
                }
            }
        }
    }
}
